package com.moonLight.weblog.admin.service.Impl;

import com.moonLight.weblog.admin.model.vo.user.FindUserInfoRspVO;
import com.moonLight.weblog.admin.model.vo.user.UpdateAdminUserPasswordReqVO;
import com.moonLight.weblog.admin.service.AdminUserService;
import com.moonLight.weblog.common.domain.dos.BlogSettingsDO;
import com.moonLight.weblog.common.domain.dos.UserDo;
import com.moonLight.weblog.common.domain.mapper.BlogSettingsMapper;
import com.moonLight.weblog.common.domain.mapper.UserMapper;
import com.moonLight.weblog.common.enums.ResponseCodeEnum;
import com.moonLight.weblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private BlogSettingsMapper blogSettingsMapper;

    /**
     * 修改密码
     * @param updateAdminUserPasswordReqVO 修改密码请求参数
     * @return
     */
    @Override
    public Response updatePassword(UpdateAdminUserPasswordReqVO updateAdminUserPasswordReqVO) {
        //拿到参数
        String username = updateAdminUserPasswordReqVO.getUsername();
        String password = updateAdminUserPasswordReqVO.getPassword();
        //密码加密
        String encode = passwordEncoder.encode(password);
        int count = userMapper.updatePasswordByUsername(username, encode);
        return count == 1 ? Response.success() : Response.fail(ResponseCodeEnum.USERNAME_NOT_FOUND);

    }

    /**
     * 查询用户信息 不需要查询数据库 从Token中获取
     * @param
     * @return
     */
    @Override
    public Response<FindUserInfoRspVO> findUserInfoRspVO() {
        //SecurityContextHolder.getContext().setAuthentication(authentication); 在之前登录接口成功之后会设置
        // 获取存储在 ThreadLocal 中的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        // 去博客详情中获取到用户的头像链接
        BlogSettingsDO blogSettingsDO = blogSettingsMapper.selectByUserName(username);
        log.warn("用户名:{}", username);
        log.warn("头像链接:{}", blogSettingsDO.getAvatar());
        return Response.success(FindUserInfoRspVO.builder().username(username).avatar(blogSettingsDO.getAvatar()).build());
    }
}
